import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_juwo/common/common_index.dart';
import 'package:flutter_juwo/provider/UserModel.dart';
import 'package:flutter_juwo/ui/controller/MyPageState.dart';
import 'package:flutter_juwo/ui/controller/NetUtils.dart';
import 'package:flutter_juwo/ui/custom/NotLoginPage.dart';
import 'package:flutter_juwo/ui/custom/noData.dart';
import 'package:flutter_juwo/ui/model/message_list_entity.dart';
import 'package:flutter_juwo/ui/res/shared_preferences_keys.dart';
import 'package:flutter_juwo/ui/utils/sp_util.dart';
import 'package:flutter_juwo/ui/utils/toast_utils.dart';

import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_easyrefresh/ball_pulse_header.dart';
import 'package:flutter_easyrefresh/ball_pulse_footer.dart';
import 'package:provider/provider.dart';

class MessageListPage extends StatefulWidget {
  @override
  _MessageListPageState createState() => _MessageListPageState();
}

class _MessageListPageState extends State<MessageListPage>
    with AutomaticKeepAliveClientMixin {
  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;

  MessageListEntity _messageListEntity = null;
  MyPageState ps = MyPageState.LOADING;

  EasyRefreshController _easyRefreshController = EasyRefreshController();

  ///当前码
  int _currentPage = 1;

  ///页数默认为1 通过 总数 计算得来
  int _pages = 1;

  ///一页 20 条数据
  int _itemNum = 20;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    print("init--1");
    this.init();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Scaffold(
      appBar: UiUtils.myAppBar(context, "消息"),
      body: Column(
        children: <Widget>[
          UiUtils.divider(),
          Expanded(
            flex: 1,
            child: Consumer<UserModel>(
              builder: (context, UserModel userModel, _) {
                return getContent();
              },
            ),
          )
        ],
      ),
    );
  }

  getContent() {
    if (SpUtil.getString(SpKeys.userToken).isEmpty) {
      ps = MyPageState.NOT_LOGIN;
    } else {
      if (ps != MyPageState.NOT_DATA) {
        ps = MyPageState.HAVE_DATA;
      }
    }

    if (ps == MyPageState.LOADING) {
      return LoadingPage();
    }
    if (ps == MyPageState.NOT_LOGIN) {
      return NotLoginPage();
    }

    if (ps == MyPageState.NOT_DATA) {
      return NoData(getData);
    }

    if (ps == MyPageState.HAVE_DATA) {
      if (null == _messageListEntity) {
        print("init--2");
        init();
        return LoadingPage();
      }
      return EasyRefresh.custom(
        controller: _easyRefreshController,

        /// firstRefresh: true,
        enableControlFinishRefresh: true,
        enableControlFinishLoad: true,
        header: BallPulseHeader(),
        footer: BallPulseFooter(),
        onRefresh: () async {
          await Future.delayed(Duration(seconds: 1), () {
            _currentPage = 1;
            print("getData--1");
            this.getData(page: _currentPage);
          });
        },
        onLoad: () async {
          await Future.delayed(Duration(seconds: 1), () {
            if (_currentPage < _pages) {
              _currentPage++;
              print("getData--2");
              this.getData(page: _currentPage);
            } else {
              _easyRefreshController.finishLoad();
              ToastUtil.showShortToast("没有更多消息了");
            }
          });
        },
        slivers: <Widget>[
          SliverList(
            delegate: SliverChildBuilderDelegate(
              (context, index) {
                return this.getItem(_messageListEntity.data.res[index]);
              },
              childCount: _messageListEntity.data.res.length,
            ),
          ),
        ],
      );
    }
    print("getData--3");
    return NoData(this.getData);
  }

  Future getData({int page = 1}) async {
    FormData formData = FormData.from({"page": page, "size": "$_itemNum"});
    DioManager.getInstance().get(Api.MESSAGE_LIST, formData, (json) {
      print("获取消息列表数据SUC：${json}");
      MessageListEntity data = MessageListEntity.fromJson(json);
      if (data.code == Api.SUCCESS_CODE) {
        ///1.判断有没有获取到数据
        if (null == data.data.res || data.data.res.length <= 0) {
          this.noData();
          return;
        }

        ///获取页数
        int all = int.parse(data.data.total);
        _pages = (all / _itemNum).ceil();
        print("页数：$_pages");

        ///2.判断本来有没有数据
        if (null == _messageListEntity) {
          _messageListEntity = data;
          this.haveData();
          return;
        }

        ///3.下拉刷新数据
        if (page == 1) {
          _currentPage = 1;
          _messageListEntity.data.res.clear();
          _messageListEntity = data;
          this.haveData();
          _easyRefreshController.finishRefresh(success: true);
          return;
        }

        ///4.上拉加载
        _messageListEntity.data.res.addAll(data.data.res);
        this.haveData();
        _easyRefreshController.finishLoad();
        return;
      }

      if (_messageListEntity.code == Api.ERROR_CODE_0 ||
          _messageListEntity.code == Api.ERROR_CODE) {
        ToastUtil.showShortErrToast(_messageListEntity.message);
        return;
      }
    }, (errMsg) {
      noData();
      ToastUtil.showShortErrToast(errMsg);
    });
  }

  ///没有数据
  void noData() {
    ps = MyPageState.NOT_DATA;
    setState(() {});
  }

  ///有数据
  void haveData() {
    ps = MyPageState.HAVE_DATA;
    setState(() {});
  }

  getItem(MessageListDataRe res) {
    return Container(
      color: Colors.white,
      child: Column(
        children: <Widget>[
          GestureDetector(
            onTap: () {
              ///跳转到详情页面
              Application.router
                  .navigateTo(context, "${Routes.messageDetails}?id=${res.id}");
            },
            child: Row(
              children: <Widget>[
                Container(
                  padding: EdgeInsets.only(
                      left: ScreenUtil().setWidth(30),
                      top: ScreenUtil().setWidth(20),
                      bottom: ScreenUtil().setWidth(20),
                      right: ScreenUtil().setWidth(15)),
                  child: Text(
                    "${res.type == "0" ? "消息" : "通知"}",
                    style: TextStyles.custom(
                        32, Colours.appC11, Font.PingFangMedium),
                  ),
                ),
                Expanded(
                  flex: 1,
                  child: Container(
                    child: Text("${res.remark}",
                        style: TextStyles.custom(
                            32, Colours.appC2, Font.PingFangMedium)),
                  ),
                ),
                Container(
                  margin:
                      EdgeInsets.fromLTRB(0, 0, ScreenUtil().setWidth(30), 0),
                  child: Text("${res.sendTime}",
                      style: TextStyles.custom(
                          32, Colours.appC3, Font.PingFangMedium)),
                ),
              ],
            ),
          ),
          UiUtils.divider()
        ],
      ),
    );
  }

  void init() {
    bool isLogin = NetUtils.isLogin();
    if (isLogin) {
      ///获取数据
      print("getData--4");
      this.getData();
    } else {
      ps = MyPageState.NOT_LOGIN;
    }
  }
}
